
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_test_demo/pages/home/components/HotOrderedPage.dart';
import 'package:flutter_test_demo/pages/home/components/OrderedPage.dart';
import 'package:flutter_test_demo/pages/home/components/RecommendInfo.dart';
import 'package:flutter_test_demo/pages/upload/UploadFile.dart';
import 'package:flutter_test_demo/static/colors/MyColors.dart';
import 'package:photo_album_manager/photo_album_manager.dart';
import 'package:toast/toast.dart';



// 推荐
class RecommendPage extends StatefulWidget {
  RecommendPage({Key key}) : super(key: key);

  @override
  _RecommendPageState createState() => _RecommendPageState();
}

class _RecommendPageState extends State<RecommendPage> {
  EasyRefreshController _controller;
  
  List<Map<String, dynamic>> hotList = [];
  @override
  void initState(){
    super.initState();
     _controller = EasyRefreshController();
     hotList = hotMessage();
  }

  Column listInfo(){
    return Column(
      children: hotList.map((e) => 
        ListTile(
          title: Text(e["title"]),
          leading: CircleAvatar(
            child: Image.asset(e['image']),
          ),
          subtitle: Text(e['des']),
          trailing: Icon(Icons.keyboard_arrow_right),
          onTap: () {
            print("object");
            // 带参数跳转
            Navigator.push(context, 
              MaterialPageRoute(
                builder: (context)=> RecommendInfo(reInfo: e)
              )
            );
          },  
        )
      ).toList(),
    );
  }

  // 点击文字效果
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: JumpSearchPage(), 
        backgroundColor: MyColor.titleColor,
        actions: <Widget>[
          PopupMenuButton<String>(
            offset: Offset(0.0,60.0),
            onSelected: (String value) async{
             if(value == "查询"){
                Navigator.of(context).pushNamed("/search");
             }else if(value == "video" || value == "photo"){
              //  检查权限
              PermissionStatus status = await PhotoAlbumManager.checkPermissions();
              //  用户同意后跳转上传页面
              if(status == PermissionStatus.granted){
                Navigator.push(
                  context, 
                  MaterialPageRoute(builder: (context) => UpLoadFile(resoureType: value),)
                );
              }else{
                Toast.show("获取权限失败，请打开相册权限", context);
              }
             }
            },
            itemBuilder: (BuildContext context) =>  <PopupMenuEntry<String>>[
              PopupMenuItem(
                child: Text("查询"),
                value: "查询",
              ),
              PopupMenuItem(
                child: Text("本地图片"),
                value: "photo",
              ),
              PopupMenuItem(
                child: Text("本地视频"),
                value: "video",
              )
            ],
          )
        ]
      ),
      body: EasyRefresh(
        onRefresh: () async {
          setState(() {
            Map obj = hotList[0];
            hotList.removeAt(0);
            hotList.add(obj);
          });
        },
        controller: _controller,
        child: ListView(
          children: <Widget>[
            BannerImages(),
            // 热门推荐标题
            Padding(
              padding: EdgeInsets.symmetric(
                vertical: 20.0,
                horizontal: 12.0
              ),
              child: Row(
                children: <Widget>[
                  DecoratedBox(
                    decoration: BoxDecoration(
                      color: MyColor.titleColor,
                    ),
                    child: ConstrainedBox(
                      constraints: BoxConstraints.tightFor(
                        width: 4.0,
                        height: 20.0
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 15.0),
                    child: Text(
                      "热门作者",
                      style: TextStyle(
                        color: MyColor.titleColor,
                        fontSize: 18.0
                      ),
                    ),
                  ),
                  Expanded(
                    child: IconButton(
                      alignment:Alignment.centerRight,
                      icon: Icon(
                        Icons.refresh,
                        color: MyColor.titleColor,
                        size: 18.0,
                      ), 
                      onPressed: (){
                        setState(() {
                          Map obj = hotList[0];
                          hotList.removeAt(0);
                          hotList.add(obj);
                        });
                      }
                    )
                  )
                ],
              ),
            ),
            
            // 热门推荐
            listInfo(),

            // 热门推荐
            HotOrderedPage(),

            // 已订阅
            OrderedPage(),

            
          ],
        ), 
      )
    );
  }
}


// 搜索
class JumpSearchPage extends StatefulWidget {
  JumpSearchPage({Key key}) : super(key: key);

  @override
  _JumpSearchPageState createState() => _JumpSearchPageState();
}

class _JumpSearchPageState extends State<JumpSearchPage> {
  
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
      child: GestureDetector(
        onTap: () {
          // 搜索页面
          Navigator.of(context).pushNamed("/search");
        },
        child: Stack(
          children: <Widget>[
            // 搜索框
            Positioned(
              child: Container(
                height: 40.0,
                width: double.infinity,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(20.0)),
                  color: MyColor.searchColor
                ),
                child: Text(
                  "请输入你想知道的..",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 15.0,
                    color: MyColor.searchFontColor,
                    height:2.0
                  ),
                ),
              ),
            ),
            // 搜索 图标
            Positioned(
              right: 10.0,
              top: 5.0,
              child: Icon(
                Icons.search,
                size: 30.0,
                color: MyColor.searchFontColor,
              )
            )
          ],
        ),
      ),
    );
  }
}

// 轮播
class BannerImages extends StatefulWidget {
  BannerImages({Key key}) : super(key: key);

  @override
  _BannerImagesState createState() => _BannerImagesState();
}

class _BannerImagesState extends State<BannerImages> {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 200.0,
      child: Swiper(
        itemBuilder: _swiperBuilder,
        itemCount: 3,
        pagination: new SwiperPagination(
            builder: DotSwiperPaginationBuilder(
          color: Colors.black54,
          activeColor: Colors.white,
        )),
        control: new SwiperControl(),
        scrollDirection: Axis.horizontal,
        autoplay: true,
        onTap: (index) => print('点击了第$index个'),
      ),
    );
  }
}

Widget _swiperBuilder(BuildContext context, int index) {
  return Image.asset('images/banner-${index + 1}.jpg', fit: BoxFit.cover);
}


// 历史列表数据
List<Map<String, dynamic>> hotMessage() {
  List<Map<String, dynamic>> data = [
      {
        "title":"Lili",
        "image": 'images/avator.jpg',
        "age":'20',
        "mm": "万紫千红一片红",
        "des":"this is describe"
      },
      {
        "title":"Huhua",
        "image": 'images/avator1.jpg',
        "age":'20',
        "mm": "万紫千红一片片",
        "des":"this is describe"
      },
      {
        "title":"Xiaog",
        "image": 'images/avator2.jpg',
        "age":'10',
        "mm": "万紫千红一片紫",
        "des":"this is describe"
      },
      {
        "title":"Xiha",
        "image": 'images/avator3.jpg',
        "age":'23',
        "mm": "万紫千红一片橙",
        "des":"this is describe"
      },
      {
        "title":"Nangua",
        "image": 'images/avator.jpg',
        "age":'21',
        "mm": "万紫千红一片灰",
        "des":"this is describe"
      },
      
    ];
 
  return data;
}